package mju.cxf.controller.user;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mju.cxf.constant.MessageConstant;
import mju.cxf.context.BaseContext;
import mju.cxf.dto.GoodsDTO;
import mju.cxf.dto.SalesAddDTO;
import mju.cxf.dto.SalesDTO;
import mju.cxf.entity.*;
import mju.cxf.exception.BaseException;
import mju.cxf.result.Result;
import mju.cxf.service.*;
import mju.cxf.service.impl.SalesServiceImpl;
import mju.cxf.vo.SalesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 商品出售相关接口
 */

@RestController
@Api(tags = "出售接口列表")
@RequestMapping("/user/api/sales")
public class ISalesController {
    @Autowired
    private SalesServiceImpl salesService;
    @Autowired
    private ProductSpecificationsService psService;
    @Autowired
    private ProductCategoriesService pcService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoriesService categoriesService;

    @PostMapping("/categories")
    @ApiOperation("出售查看全部分类")
    public Result<List<Categories>> saleCategories() {
        LambdaQueryWrapper<Categories> cqw = new LambdaQueryWrapper<>();
        cqw.eq(Categories::getState, 0);
        return Result.success(categoriesService.list(cqw));
    }

    @PostMapping("/product")
    @ApiOperation("出售查看分类商品")
    public Result<List<Product>> saleProduct(@RequestBody int categoryId) {
        LambdaQueryWrapper<ProductCategories> cqw = new LambdaQueryWrapper<>();
        cqw.eq(ProductCategories::getCategoriesId, categoryId);
        final List<ProductCategories> productCategories = pcService.list(cqw);
        List<Integer> ids = productCategories.stream()
                .map(ProductCategories::getProductId) // 替换成你需要获取的属性
                .collect(Collectors.toList());
        LambdaQueryWrapper<Product> pqw = new LambdaQueryWrapper<>();
        pqw.in(Product::getId, ids).eq(Product::getState, 0);
        return Result.success(productService.list(pqw));
    }

    @PostMapping("/specifications")
    @ApiOperation("出售查看商品规格")
    public Result<List<ProductSpecifications>> saleSpecifications(@RequestBody int goodsId) {
        LambdaQueryWrapper<ProductSpecifications> pqw = new LambdaQueryWrapper<>();
        pqw.eq(ProductSpecifications::getProductId, goodsId)
           .eq(ProductSpecifications::getState, 0);

        return Result.success(psService.list(pqw));
    }

    /**
     * 新增出售信息
     *
     * @return 新增结果
     */
    @PostMapping("/add")
    @ApiOperation(value = "新建商品信息")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> createProduct(@RequestBody SalesAddDTO salesAddDTO) {
        List<String> cdKeys = salesAddDTO.getSales().stream()
                .map(Sales::getCdKey)
                .collect(Collectors.toList());
        LambdaQueryWrapper<Sales> sqw1=new LambdaQueryWrapper<>();
        sqw1.in(Sales::getCdKey,cdKeys).ne(Sales::getState, 6);//并且不等于取消
        final List<Sales> salesList = salesService.list(sqw1);
        System.out.println(salesList);
        if (!salesList.isEmpty()) {
            return Result.error("未取消卡密");
        }
        AtomicInteger success= new AtomicInteger();
        AtomicInteger warn= new AtomicInteger();
        List<Sales> cardInfos = salesAddDTO.getSales();
        List<Sales> collect = cardInfos.stream().peek((sales) -> {
            if (sales.getKeyOutTime()==null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    // 将字符串转换为 Date 对象
                try {
                    Date date = formatter.parse("2099-09-09");
                    sales.setKeyOutTime(date);
                } catch (ParseException e) {
                    throw new BaseException(e.getMessage());
                }
            }
            final Integer shelfDay = salesAddDTO.getShelfDay();
            // 获取当前日期
            Date currentDate = new Date();

            // 加上 ShelfDay 的天数
            Date newDate = shelfDay>0&&shelfDay<8?
                    DateUtil.offsetDay(currentDate, shelfDay):
                    DateUtil.offsetDay(currentDate, 365);
            sales.setShelfDays(shelfDay>0&&shelfDay<8?shelfDay:365);
            sales.setShelfTime(newDate);
            sales.setAmount(salesAddDTO.getAmount());
            sales.setProductId(salesAddDTO.getProductId());
            sales.setSalesNumber("CSDD"+System.currentTimeMillis()+success);
            sales.setSpecificationsId(salesAddDTO.getSpecificationsId());
            sales.setUserId(BaseContext.getCurrentId());
            sales.setCreateTime(LocalDate.from(LocalDateTime.now()));
        }).filter((sales -> {
            LambdaQueryWrapper<Sales> sqw=new LambdaQueryWrapper<>();
            sqw.eq(Sales::getProductId, salesAddDTO.getProductId()).eq(Sales::getCdKey,sales.getCdKey());
            if (salesService.getOne(sqw) != null) {
                warn.getAndIncrement();
                return false;
            }
            success.getAndIncrement();
            return true;
        })).collect(Collectors.toList());
        boolean b=false;
        if (!collect.isEmpty()){
           b = salesService.saveBatch(collect);
        }
        String msg="成功了:"+success+"条,"+"失败了:"+warn+"条";
        return b && warn.get()==0? Result.success(MessageConstant.SUCCESS_MESSAGE) : Result.error(MessageConstant.FAILURE_MESSAGE,msg);


    }
    @PostMapping("/count")
    private Result<Long> salesCount(@RequestBody int goodsId) {
        LambdaQueryWrapper<Sales> qw = new LambdaQueryWrapper<>();
        qw.eq(Sales::getState, 2).eq(Sales::getSpecificationsId,goodsId);
        long count =salesService.count(qw);
        return Result.success(count);
    }


    /**
     * 分页查询出售信息
     *
     * @param name    可选，根据用户名进行模糊查询
     * @param state   可选，根据出售状态进行查询
     * @param current 当前页码
     * @param size    每页显示的记录数
     * @return 分页查询结果
     */
    @GetMapping("/pages")
    @ApiOperation(value = "分页查询出售信息", notes = "根据用户名和出售状态分页查询")
    public Page<SalesDTO> getUsersByUsernameAndState(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "state", required = false) Integer state, // 添加状态参数
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        return salesService.selectPageByNameAndState(name, state, current, size);
    }
    @PostMapping("/getOne")
    public Result<HashMap<String,Object>> getOneGoods(@RequestBody GoodsDTO goodsDTO) {
        if (goodsDTO==null){
            throw new BaseException("业务异常");
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("categories",categoriesService.getById(goodsDTO.getCategoryId()));
        map.put("product",productService.getById(goodsDTO.getProductId()));
        map.put("goods",psService.getById(goodsDTO.getGoodsId()));
        return Result.success(map);
    }
    /**
     * U分页查询出售信息
     *
     * @param name    可选，根据用户名进行模糊查询
     * @param state   可选，根据出售状态进行查询
     * @param current 当前页码
     * @param size    每页显示的记录数
     * @return 分页查询结果
     */
    @GetMapping("/salesList")
    @ApiOperation(value = "分页查询出售信息", notes = "根据用户名和出售状态分页查询")
    public Result<HashMap<String, Object>> salesPage(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "state", required = false) Integer state, // 添加状态参数
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        Page<Sales> page = new Page<>(current, size);
        LambdaQueryWrapper<Sales> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Sales::getUserId, BaseContext.getCurrentId()).orderByDesc(Sales::getId);
        if (state != null) {
            lqw.eq(Sales::getState, state);
        }
        final Page<Sales> salesPage = salesService.page(page, lqw);
        final List<SalesVO> salesVOList = salesPage.getRecords().stream().map(sales -> SalesVO.builder()
                .goods(psService.getById(sales.getSpecificationsId()))
                .sales(sales)
                .build()).collect(Collectors.toList());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("total", salesPage.getTotal());
        hashMap.put("rows", salesVOList);
        hashMap.put("pages", salesPage.getPages());
        hashMap.put("current", salesPage.getCurrent());
        return Result.success(hashMap);
    }

    /**
     * 查看订单卡密
     * @return
     */
    @PostMapping("/look")
    public Result<List<Sales>> salesLookKey(@RequestParam String orderNumber){
        LambdaQueryWrapper<Sales> qw = new LambdaQueryWrapper<>();
        qw.eq(Sales::getOrderNumber, orderNumber).isNull(Sales::getAfterId);
        return Result.success(salesService.list(qw));
    }

    /**
     * 上下架 出售取消
     * @return
     */
    @PostMapping("/upperAndLowerShelves")
    public Result<String> upperAndLowerShelves(@RequestParam String salesNumber,@RequestParam int status){
        LambdaUpdateWrapper<Sales> suw = new LambdaUpdateWrapper<>();
        suw.eq(Sales::getSalesNumber, salesNumber).set(Sales::getState, status);
        String msg=status==2?"上架成功":status==6?"取消成功":"下架成功";
        return salesService.update(suw)?Result.success(msg):Result.error(MessageConstant.FAILURE_MESSAGE);
    }
}
